/*
 * Copyright (c) 2013-2015 Marco Ziccardi, Luca Bonato
 * Licensed under the MIT license.
 */


package org.havenapp.main.sensors.motion;


import android.util.Log;

import java.util.ArrayList;
import java.util.List;

public class LuminanceMotionDetector implements IMotionDetector {

    /**
     * Difference in luma for each pixel
     */
    private int valueThreshold = 50;
    /**
     * Difference in number of pixel for each image
     */
    private int numberThreshold = 5000;

    /**
     * Levels of motion detection
     */
    public static final int MOTION_MEDIUM = 30000;

    /**
     * Sets different sensitivity for the algorithm
     *
     * @param thresh sensitivity identifier
     */
    @Override
    public void setThreshold(int thresh) {
        numberThreshold = thresh;
        valueThreshold = thresh / 1000;
    }

    /**
     * (non-Javadoc)
     *
     * @see me.ziccard.secureit.motiondetection.IMotionDetector#detectMotion(int[], int[], int, int)
     */
    @Override
    public List<Integer> detectMotion(int[] oldImage, int[] newImage, int width,
                                      int height) {
        if (oldImage == null || newImage == null) {
            throw new NullPointerException();
        }
        if (oldImage.length != newImage.length) {
            throw new IllegalArgumentException();
        }

        ArrayList<Integer> differentPixels = new ArrayList<>();
        int differentPixelNumber = 0;
        Log.e("buxq", "width = " + (width));
        Log.e("buxq", "height = " + (height));
        Log.e("buxq", "height*width = " + (height * width));
        for (int ij = 0; ij < height * width; ij++) {
            int newPixelValue = newImage[ij];
            int oldPixelValue = oldImage[ij];
            if (Math.abs(newPixelValue - oldPixelValue) >= valueThreshold) {
                differentPixelNumber++;
                differentPixels.add(ij);
            }
        }

        if (differentPixelNumber > numberThreshold) {
            return differentPixels;
        }

        return null;
    }

}
